package fmt_sfe

import (
	"fmt"
	"strings"
)

const EnumPrefix = "E"

type FieldEnumUnit struct {
	name string // enum name

	adding    bool // 添加现有的
	inserting bool // 添加新的中

	members []string // 已存在的
	fields  []string // 结构体原封不动保存
} //
func (this *FieldEnumUnit) addMember(line string) {
	if strings.HasPrefix(line, "//") {
		return
	}
	//fmt.Println("addMember", line)
	this.members = append(this.members, line)
}
func (this *FieldEnumUnit) insertField(line string) {
	if strings.HasPrefix(line, "//") {
		return
	}
	idx := strings.Index(line, "json:")
	if idx == -1 {
		return
	}
	tag := strings.Split(line[idx:], "\"")[1]
	if tag == "-" {
		return
	}
	//fmt.Println("insertField", tag)
	this.fields = append(this.fields, tag)
}

func (this *FieldEnumUnit) fmtstr() string {
	final := []string{}
	for _, f := range this.fields {
		if idx := this.Existed(f); idx != -1 {
			final = append(final, "\t"+this.members[idx])
			continue
		}

		final = append(final, fmt.Sprintf("\tE%sF_%s", this.name, Case2Camel(f)))
	}
	final = append(final, fmt.Sprintf("\tE%sF_Max", this.name))
	return fmt.Sprintf(enum_fmt, this.name, final[0], this.name, strings.Join(final[1:], "\n"))
}
func (this *FieldEnumUnit) Existed(field string) int {
	v := fmt.Sprintf("E%sF_%s", this.name, field)
	for i, m := range this.members {
		if m == v {
			return i
		}
	}
	return -1
}

// 驼峰式写法转为下划线写法
func Camel2Case(s string) string {
	data := make([]byte, 0, len(s)*2)
	j := false
	num := len(s)
	for i := 0; i < num; i++ {
		d := s[i]
		if i > 0 && d >= 'A' && d <= 'Z' && j {
			data = append(data, '_')
		}
		if d != '_' {
			j = true
		}
		data = append(data, d)
	}
	return strings.ToLower(string(data[:]))
}

// 下划线写法转为驼峰写法
func Case2Camel(name string) string {
	name = strings.Replace(name, "_", " ", -1)
	name = strings.Title(name)
	return strings.Replace(name, " ", "", -1)
}

//------------------------------------------------------------------------------
const enum_fmt = `type E%sField int //
const (
%s  E%sField = iota + 1
%s
)
`
